package com.mazaiting.rabbitmq.callback;

import com.mazaiting.common.core.domain.result.ResultCode;
import com.mazaiting.common.core.ex.runtime.ValidationException;
import com.mazaiting.rabbitmq.domain.entity.MqMessage;
import com.mazaiting.rabbitmq.service.IMqMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * 生产端消息确认回调
 *
 * @author mazaiting
 * @create_time 2022/4/1 19:20
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ConfirmCallback implements RabbitTemplate.ConfirmCallback {

    private final IMqMessageService mqMessageService;

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (Objects.isNull(correlationData) || !StringUtils.hasLength(correlationData.getId())) {
            log.error("消息 ID 为空");
            return;
        }
        // 消息 ID
        String messageId = correlationData.getId();
        log.info("消息 [{}] 发送结果: {}", messageId, ack);
        // 根据 ID 获取消息
        MqMessage mqMessage = mqMessageService.getById(messageId);
        if (Objects.isNull(mqMessage)) {
            throw new ValidationException(ResultCode.MQ_MESSAGE_EMPTY);
        }
        // 判断是否发送成功
        if (ack) {
            mqMessage.setSendStatus(true);
        } else {
            log.error("消息异常: {}", cause);
            mqMessage.setSendStatus(false);
            mqMessage.setErrorMsg(cause);
        }
        mqMessageService.updateById(mqMessage);
    }
}
